package com.zp.study.scloud.consumer.ctrl;

import com.alibaba.fastjson.JSONObject;
import com.zp.study.scloud.consumer.utils.HttpUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.Map;

/**
 * 测试服务与认证服务器之间的交互
 */
@RestController
@RequestMapping("/test/oauth2")
public class OAuth2TestCtrl {
    @Autowired
    private RestTemplate restTemplate;

    /**
     * 获取code的接口回调
     * 需要在认证服务器配置此接口，见 com.zp.study.scloud.oauth2.config.AuthorizationServerConfiguration 里的redirectUris配置
     * 流程：客户端向认证服务器发起请求获取code -> 认证服务器展示登录页面 -> 用户登录 -> 登录成功后认证服务器将code发送给本回调接口
     * @return
     */
    @GetMapping("/authCodeCallBack")
    public Object authCodeCallBack(String code){
        // 获取到授权code，通过code、client_id、secret获取token
        String clientId = "client_id_1"; // 客户端id 认证服务器事先分配
        String clientSecret = "client_id_1_secret";// 客户端密钥  认证服务器事先分配
        String tokenRest = HttpUtils.doPost(
                "http://" + clientId + ":" + clientSecret + "@localhost:8060/oauth/token",// 注意请求链接的结构
                new HashMap(){{
                    put("grant_type","authorization_code");
                    put("code",code);
                }},
                new HashMap(){{
                    put("Content-Type","application/x-www-form-urlencoded");
                }}
        );
        if(tokenRest == null || tokenRest.equals("")) return "ERROR: 获取token失败";
        //{"access_token":"17635b81-6cd7-493d-83b1-4e28a866be70","token_type":"bearer","expires_in":43199,"scope":"app"}
        JSONObject tokenRestObj = JSONObject.parseObject(tokenRest);
        String access_token = (String) tokenRestObj.get("access_token");
        String expires_in = (String) tokenRestObj.get("expires_in");
        String scope = (String) tokenRestObj.get("scope");

        // 获取到token，在请求资源时，带上此token才可以通过验证

        return "";
    }

}
